<?php 
    require_once ("/mnt/sdcard/www/Includes/simplecms-config.php");
    require_once  ("/mnt/sdcard/www/Includes/connectDB.php");
    include("/mnt/sdcard/www/Includes/header.php");

    $sessionTeam = $_SESSION['team'];
    $sessionName = $_SESSION['name'];

    if (!logged_on())
    {
        echo "
            <div class='alert alert-danger'>
                <strong>접근 오류!</strong> 로그인 후에 이용할 수 있는 서비스 입니다.
            </div>
        ";
    }

    if(isset($_POST['device_lend']))
    {
        $list = $_POST['list'];
    }
    elseif(isset($_POST['device_del']))
    {
        $list = $_POST['list'];

        for($i=0; $i<count($list); $i++)
        {
            $query = "UPDATE deviceInfo set deleted='1' WHERE id='$list[$i]'";
            $statement = $databaseConnection->prepare($query);
            $statement->execute();
            $statement->store_result();
        }

        $creationWasSuccessful = $statement->affected_rows == 1 ? true : false;
        if ($creationWasSuccessful)
        {
            $statement->close();
            echo("
                <script>
                window.alert('삭제되었습니다.')
                location.replace('phoneList.php')
                </script>
            ");
            exit;
        }
        else
        {
            $statement->close();
            echo("
                <script>
                window.alert('삭제를 실패했습니다.')
                location.replace('phoneList.php')
                </script>
            ");
            exit;
        }
    }

    if(isset($_POST['send']))
    {
        $lendList = $_POST['lendList'];
        $team = $_POST['team'];
        $name = $_POST['name'];
        $startDate = $_POST['startDate'];
        $endDate = $_POST['endDate'];
        $cable = $_POST['cable'];
        $etc = $_POST['etc'];

        $creationWasSuccessful = true;

        for($i=0; $i<count($lendList); $i++)
        {
            /*
            $query = "UPDATE deviceInfo set team='$team[$i]', name='$name[$i]', startDate='$startDate[$i]', endDate='$endDate[$i]', etc='$etc[$i]', deviceState='1' WHERE id='$lendList[$i]'";
            $statement = $databaseConnection->prepare($query);
            $statement->execute();
            $statement->store_result();

            $queryLend = "INSERT INTO users_lend (device_id, user_id, cable, date, returnedDate, returned) VALUES (?, ?, ?, Now(), '', 0)";
            $statementLend = $databaseConnection->prepare($queryLend);
            $statementLend->bind_param('iii', $lendList[$i], $_SESSION['userid'], $cable[$i]);
            $statementLend->execute();
            $statementLend->store_result();
            */

            $query = "UPDATE deviceInfo set deviceState=3 WHERE id=$lendList[$i]";
            $statement_deviceInfo = $databaseConnection->prepare($query);
            $statement_deviceInfo->execute();
            $statement_deviceInfo->store_result();

            $query = "INSERT INTO approval (device_id, user_id, request_date, approval_date, approval_type, approval_state, start_date, end_date, cable, etc) VALUES (?, ?, Now(), '', 1, 0, ?, ?, ?, ?)";
            //echo $query;
            //echo "lendList: " . $lendList[$i] . ", userid: " . $_SESSION['userid'] . ", startDate: " . $startDate[$i] . ", endDate: " . $endDate[$i] . ", cable: " . $cable[$i] . ", etc: " . $etc[$i];
            $statement_approval = $databaseConnection->prepare($query);
            $statement_approval->bind_param('iissis', $lendList[$i], $_SESSION['userid'], $startDate[$i], $endDate[$i], $cable[$i], $etc[$i]);
            $statement_approval->execute();
            $statement_approval->store_result();

            $creationWasSuccessful = ($statement_approval->affected_rows == 1 ? true : false) && $creationWasSuccessful;
        }

        if ($creationWasSuccessful)
        {
            $statement_approval->close();
            $statement_deviceInfo->close();
            echo("
                <script>
                window.alert('신청되었습니다.')
                location.replace('approval.php')
                </script>
            ");
            //header ("Location: phoneList.php");
        }
        else
        {
            $statement_approval->close();
            $statement_deviceInfo->close();
            echo("
                <script>
                window.alert('신청에 실패했습니다.')
                location.replace('phoneList.php')
                </script>
            ");
        }
    }
?>

<div class="navbar navbar-inverse navbar-fixed-top">
    <div class="container">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            </button>
            <?php
                if (logged_on())
                {
                    $url = "/phoneList.php";
                }
                else
                {
                    $url = "/index.php";
                }
            ?>
            <a class="navbar-brand" href="<?php echo $url ?>">Device Management System</a>
        </div>
        <div class="navbar-collapse collapse">
            <ul class="nav navbar-nav">
                <li><a href="/index.php">Home</a></li>
                <?php
                    if (logged_on())
                    {
                        echo '
                            <li class="active"><a href="/phoneList.php">기기목록</a></li>
                            <li><a href="/approval.php">결재</a></li>
                        ';
                    }
                ?>
                <?php
                    if (is_admin())
                    {
                        echo '
                            <li class="dropdown">
                            <a href="#" class="dropdown-toggle" data-toggle="dropdown">관리메뉴<b class="caret"></b></a>
                                <ul class="dropdown-menu">
                                    <li><a href="/phoneEnroll.php">기기등록</a></li>
                                    <li><a href="/manage.php">기기관리</a></li>
                                    <!--<li class="divider"></li>
                                    <li class="dropdown-header">Nav header</li>
                                    <li><a href="#">Separated link</a></li>
                                    <li><a href="#">One more separated link</a></li>-->
                                </ul>
                            </li>
                        ';
                    }
                ?>
            </ul>
            <ul class="nav navbar-nav navbar-right">
                <?php
                    if (logged_on())
                    {
                        if (is_admin())
                        {
                            echo "
                                <li><a href='#'>환영합니다, {$_SESSION['username']}(관리자)</a></li>
                                <li><a href='/logoff.php'>로그아웃</a></li>
                            ";
                        }
                        elseif (is_member())
                        {
                            echo "
                                <li><a href='#'>환영합니다, {$_SESSION['username']}(정회원)</a></li>
                                <li><a href='/logoff.php'>로그아웃</a></li>
                            ";   
                        }
                        else
                        {
                            echo "
                                <li><a href='#'>환영합니다, {$_SESSION['username']}(준회원)</a></li>
                                <li><a href='/logoff.php'>로그아웃</a></li>
                            ";
                        }
                    }
                ?>
            </ul>
        </div><!--/.navbar-collapse -->
    </div>
</div>

<div class="container">
    <p><form action="phoneLend.php" method="post"><button type="submit" name="send" class="btn btn-primary">대여신청</button>
        <button type="button" class="btn btn-danger" onclick="location.href='http://210.90.237.56/phoneList.php'";>취소</button></p>
    <?php
        if(count($list))
        {
            $query = "SELECT * FROM deviceInfo WHERE (id='$list[0]'";

            for($i=1; $i<count($list); $i++)
            {
                $query .= "or id='$list[$i]'";
            }
            $query .= ") and (deviceState='0' or deviceState='3')";

            echo("
                <div class='table-responsive'>
                    <div class='panel panel-primary'>
                        <div class='panel-heading'>대여목록</div>
                            <table class='table table-hover table-striped'>
                                <thead><tr>
                                    <th>운영체제</th>
                                    <th>모델명</th>
                                    <th>해상도</th>
                                    <th>버전</th>
                                    <th>기기명</th>
                                    <th>통신사</th>
                                    <th>번호</th>
                                    <th class='text-center'>팀</th>
                                    <th class='text-center'>이름</th>
                                    <th class='text-center'>대여시작일</th>
                                    <th class='text-center'>대여종료일</th>
                                    <th class='text-center'>케이블</th>
                                    <th>대여사유</th>
                                </tr></thead>
            ");

            $statement = $databaseConnection->prepare($query);
            $statement->execute();
            $statement->store_result();
            $statement->bind_result($id, $deviceOS, $deviceName, $deviceModel, $deviceVersion, $deviceResolution, $team, $name, $startDate, $endDate, $returnDate, $carrier, $deviceNumber, $etc, $deviceID, $deviceState, $deviceOwner, $deleted);

            //$currentDate = date("Y")."-".date("m")."-".date("d");
            $currentDate = date("Y-m-d");
            $pickerID = 0;
            while($statement->fetch())
            {
                echo("
                        <tr>
                            <td><input type=hidden name=lendList[] value=$id>$deviceOS</td>
                            <td>$deviceModel</td>
                            <td>$deviceResolution</td>
                            <td>$deviceVersion</td>
                            <td>$deviceName</td>
                            <td>$carrier</td>
                            <td>$deviceNumber</td>
                            <td class='text-center'><input type=text class='form-control input-sm' placeholder='팀' name=team[] size=10 value=$sessionTeam></td>
                            <td class='text-center'><input type=text class='form-control input-sm' placeholder='이름' name=name[] size=10 value=$sessionName></td>
                            <td class='text-center'><input type=text class='form-control input-sm' placeholder='0000-00-00' name=startDate[] size=10 value=$currentDate id='dp1'></td>
                            <td class='text-center'><input type=text class='form-control input-sm' placeholder='0000-00-00' name=endDate[] size=10 value=$currentDate id='dp1-1'></td>
                            <td class='text-center'>
                                <select class='form-control input-sm' name=cable[]>
                                    <option value=0>대여안함</option>
                                    <option value=1>USB케이블</option>
                                    <option value=2>충전기</option>
                                    <option value=3>USB케이블+충전기</option>
                                </select>
                            </td>
                            <td><textarea class='form-control input-sm' rows='1' name=etc[]></textarea></td>
                        </tr>
                ");
                $pickerID++;
            }
        }
        else
        {
           echo("
                <script>
                window.alert('선택된 기기가 없습니다.')
                location.replace('phoneList.php')
                </script>
            ");
            exit; 
        }
    ?>
    </table>
    </div>
    </div>
    </form>
    <?php $statement->close();?>
</div>

<?php 
    include ("/mnt/sdcard/www/Includes/footer.php");
 ?>